// 进行token校验
const jwt = require('jsonwebtoken');
const { createConnection } = require('mysql');
const config = require('./config');
const { getOne } = require('../db');
// 验证token的函数
let user_type;
let user_name;
let user_id;
async function tokenVerify(token) {
  let flag = false;
  try {
    await jwt.verify(
      token,
      config.token.secretKey,
      async function (err, decode) {
        if (err) {
          // 当token过期，或这是一个伪造的token，或这是无效的token时会触发此逻辑
          //console.log(err);
        } else {
          // 获得解密后的token
          //console.log(decode); //{ user_name: 'jack', iat: 1660373312, exp: 1660459712 }
          // 根据这个token将确认用户是否是超管
          user_name = decode.user_name;
          let sql = `select user_id,user_type from user where user_name='${decode.user_name}'`;
          console.log(decode);
          const data = await getOne(sql);
          user_type = data.user_type;
          user_id = data.user_id;
          console.log(user_type);
          if (user_type == 1 || user_type == 2) {
            flag = true;
          }
        }
      }
    );
    return flag;
  } catch (err) {
    return false;
  }
}
// 导出token验证中间件
module.exports = {
  async isValidToken(req, res, next) {
    let bearerToken = req.headers.authorization;
    // 没有token bearerToken会是undefined
    if (bearerToken) {
      let token = bearerToken.split(' ')[1];
      let isValid = await tokenVerify(token);
      if (isValid) {
        console.log(user_type);
        res.send({
          code: 0,
          message: '凭证有效',
          result: { user_type, user_id, user_name },
        });
      } else {
        res.send({
          code: 403,
          message: '403 forbidden，当前凭证已失效，请重新登录',
        });
      }
    } else {
      res.send({
        code: 401,
        message: '请先登录',
      });
    }
  },
};
